package com.qinglei.recoup.system.task;

import com.aliyun.iot20180120.models.CreateOTAStaticUpgradeJobResponseBody;
import com.aliyun.iot20180120.models.ListOTAFirmwareResponseBody;
import com.aliyun.iot20180120.models.ListOTATaskByJobResponseBody;
import com.aliyun.iot20180120.models.QueryOTAJobResponseBody;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qinglei.recoup.common.domain.CommonConstant;
import com.qinglei.recoup.common.domain.RadarMessage;
import com.qinglei.recoup.common.domain.RadarVersionEnum;
import com.qinglei.recoup.common.service.RedisService;
import com.qinglei.recoup.common.service.impl.ProductCache;
import com.qinglei.recoup.system.domain.Bed;
import com.qinglei.recoup.system.domain.RadarUpVersionVo;
import com.qinglei.recoup.system.domain.VersionJob;
import com.qinglei.recoup.system.enums.IocUpdateEnum;
import com.qinglei.recoup.system.manager.BreathHeartAlarmV3;
import com.qinglei.recoup.system.manager.BreathHeartAlarmV4;
import com.qinglei.recoup.system.manager.BreathHeartAlarmV7;
import com.qinglei.recoup.system.service.BedService;
import com.qinglei.recoup.system.service.RadarService;
import com.qinglei.recoup.system.service.VersionJobService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 雷达相关定时任务
 */
@Slf4j
@Component
public class RadarTask {

    @Autowired
    private RedisService redisService;

    @Resource
    private BedService bedService;
    @Resource
    private BreathHeartAlarmV4 breathHeartAlarmV4;
    @Resource
    private BreathHeartAlarmV3 breathHeartAlarmV3;
    @Resource
    private BreathHeartAlarmV7 breathHeartAlarmV7;
    @Resource
    private VersionJobService versionJobService;

    public void checkRadarOffline() {
        log.info("checkRadarOffline run");
        try {
            long expire = System.currentTimeMillis() / 1000;
            // 检查已经结束的巡查时间段
            Set<String> timeoutRadars = redisService.zrangeByScore(CommonConstant.ONLINE_RADAR_ZSET_PREFIX,
                    "-inf", String.valueOf(expire));
            if (CollectionUtils.isNotEmpty(timeoutRadars)) {
                log.info("checkRadarOffline offline sns: {}", timeoutRadars);
                timeoutRadars.forEach(sn -> {
                    try {
                        RadarMessage radarMessage = new RadarMessage();
                        radarMessage.setSn(sn);
                        radarMessage.setType(RadarMessage.TYPE_DEVICE_STATUS);
                        radarMessage.setData(RadarMessage.STATUS_OFFLINE);
                        radarMessage.setTimestamp(System.currentTimeMillis());
                        bedService.procRadarData(radarMessage, true);
                        redisService.zrem(CommonConstant.ONLINE_RADAR_ZSET_PREFIX, sn);
                        Bed bed = bedService.getBedBySn(sn);
                        if (bed != null) {
                            if (RadarVersionEnum.VERSION_V4.getCode().equals(bed.getRadarVersion())) {
                                breathHeartAlarmV4.clearAlearm(bed.getId());
                            } else if (RadarVersionEnum.VERSION_V3.getCode().equals(bed.getRadarVersion())) {
                                breathHeartAlarmV3.clearAlearm(bed.getId());
                            }else if(RadarVersionEnum.VERSION_V7.getCode().equals(bed.getRadarVersion())){
                                breathHeartAlarmV7.clearAlearm(bed.getId());
                            }
                        }
                    } catch (Exception e) {
                        log.error("checkRadarOffline procRadarData error sn:{}", sn, e);
                    }
                });
            }
        } catch (Exception e) {
            log.error("checkRadarOffline error", e);
        }
    }


    public void checkRadarNetwork30s() {
        //雷达网络检测，30s-60s 没有接收到数据没有认为雷达网络不好，请检查网络  大于60s认为雷达是离线状态，优先离线状态
        log.info("checkRadarNetwork run");
        try {
            long expire = System.currentTimeMillis() / 1000;
            // 检查已经结束的巡查时间段
            Set<String> timeoutRadars = redisService.zrangeByScore(CommonConstant.NETWORK_RADAR_ZSET_PREFIX,
                    "-inf", String.valueOf(expire));
            if (CollectionUtils.isNotEmpty(timeoutRadars)) {
                log.info("checkRadarNetwork e sns: {}", timeoutRadars);
                timeoutRadars.forEach(sn -> {
                    try {
                        redisService.zrem(CommonConstant.NETWORK_RADAR_ZSET_PREFIX, sn);
                        Bed bed = bedService.getBedBySn(sn);
                        if (bed != null) {
                            UpdateWrapper<Bed> updateWrapper = new UpdateWrapper<>();
                            updateWrapper.eq("id", bed.getId()).set("is_radar_network", 1);
                            bedService.getBaseMapper().update(null, updateWrapper);
                        }
                    } catch (Exception e) {
                        log.error("checkRadarNetwork procRadarData error sn:{}", sn, e);
                    }
                });
            }
        } catch (Exception e) {
            log.error("checkRadarNetwork error", e);
        }
    }

    //雷达设备更新定时任务
    public void updateRadarVersion() {
        log.info("updateRadarVersion run");
        versionJobService.updateRadarVersion();
        log.info("updateRadarVersion stop");
    }
    //查询并更新设备状态
    public void queryAndUpdateStatus(){
        log.info("queryAndUpdateStatus run");
        versionJobService.queryAndUpdateStatus();
        log.info("queryAndUpdateStatus stop");
    }

}
